<template>
  <ToolbarButton
    type="dropdown"
    icon="i-ri-line-height"
    title="行距"
    dropdown-icon="i-ri-arrow-down-s-fill"
    popover-width="120px"
    popover-placement="bottom-start"
    @main-click="setDefaultLineHeight"
  >
    <template #dropdown>
      <ul class="line-height-dropdown">
        <DropdownItem
          v-for="option in lineHeightOptions"
          :key="option.value"
          :class="{ 'is-selected': currentLineHeight === option.value }"
          @click="setLineHeight(option.value as number)"
        >
          <span class="line-height-label">{{ option.label }}</span>
          <i
            v-if="currentLineHeight === option.value"
            class="line-height-check i-ri-check-line"
          ></i>
        </DropdownItem>
      </ul>
    </template>
  </ToolbarButton>
</template>

<script setup lang="ts">
import { inject, ref, watch, computed, onBeforeUnmount, type Ref } from "vue";
import type { Editor } from "@tiptap/vue-3";
import type { EditorProps } from "../../../../types";
import ToolbarButton from "../../../button/index.vue";
import { DropdownItem } from "../../../dropdown";
import { defaultDicts } from "../../../../config/constants";

defineOptions({
  name: "LineHeight",
});

// 注入编辑器实例和配置
const editor = inject<Ref<Editor>>("editor");
const editorProps = inject<EditorProps>("editorProps");

// 行距选项 - 从 editorProps.dicts.lineHeights 获取，如果没有则使用默认值
const lineHeightOptions = computed(() => {
  const lineHeights =
    editorProps?.dicts?.lineHeights || defaultDicts.lineHeights || [];
  const locale = editorProps?.locale || "zh-CN";
  return lineHeights.map((item: any) => {
    // 处理国际化标签，根据 locale 选择对应的语言
    let label: string;
    if (typeof item.label === "string") {
      label = item.label;
    } else if (typeof item.label === "object") {
      label =
        (locale === "zh-CN" ? item.label?.zh_CN : item.label?.en_US) ||
        item.label?.zh_CN ||
        item.label?.en_US ||
        String(item.value);
    } else {
      label = String(item.value);
    }
    return {
      label,
      value: item.value,
    };
  });
});

// 当前行距
const currentLineHeight = ref<number | null>(null);

// 获取当前行距
const getCurrentLineHeight = () => {
  if (!editor?.value) return null;

  const { selection } = editor.value.state;
  const { $from } = selection;
  const node = $from.parent;

  // 获取当前节点或段落节点的行距
  if (node && node.attrs.lineHeight) {
    return node.attrs.lineHeight;
  }

  // 检查是否有选中内容
  const { from, to } = selection;
  let foundLineHeight: number | null = null;

  editor.value.state.doc.nodesBetween(from, to, (node) => {
    if (node.attrs.lineHeight && !foundLineHeight) {
      foundLineHeight = node.attrs.lineHeight;
    }
  });

  return foundLineHeight || null;
};

// 设置默认行距（主按钮点击）- 使用 1.5
const setDefaultLineHeight = () => {
  if (!editor?.value) return;

  editor.value.chain().focus().setLineHeight(1.5).run();
  currentLineHeight.value = 1.5;
};

// 设置行距（下拉选项点击）
const setLineHeight = (lineHeight: number) => {
  if (!editor?.value) return;

  editor.value.chain().focus().setLineHeight(lineHeight).run();
  currentLineHeight.value = lineHeight;
};

// 监听编辑器变化，同步当前行距状态
watch(
  () => editor?.value,
  (newEditor, oldEditor) => {
    // 清理旧编辑器的事件监听
    if (oldEditor && (oldEditor as any)._lineHeightHandlers) {
      const handlers = (oldEditor as any)._lineHeightHandlers;
      oldEditor.off("update", handlers.update);
      oldEditor.off("selectionUpdate", handlers.selectionUpdate);
      delete (oldEditor as any)._lineHeightHandlers;
    }

    if (newEditor) {
      // 初始化时获取当前行距
      currentLineHeight.value = getCurrentLineHeight();

      // 保存事件处理函数引用以便清理
      const updateHandler = () => {
        currentLineHeight.value = getCurrentLineHeight();
      };
      const selectionUpdateHandler = () => {
        currentLineHeight.value = getCurrentLineHeight();
      };

      // 监听编辑器更新，同步当前行距
      newEditor.on("update", updateHandler);

      // 监听选择变化，同步当前行距
      newEditor.on("selectionUpdate", selectionUpdateHandler);

      // 保存引用以便清理（挂载到编辑器实例上）
      (newEditor as any)._lineHeightHandlers = {
        update: updateHandler,
        selectionUpdate: selectionUpdateHandler,
      };
    }
  },
  { immediate: true }
);

// 组件卸载时清理事件监听器
onBeforeUnmount(() => {
  if (editor?.value && (editor.value as any)._lineHeightHandlers) {
    const handlers = (editor.value as any)._lineHeightHandlers;
    editor.value.off("update", handlers.update);
    editor.value.off("selectionUpdate", handlers.selectionUpdate);
    delete (editor.value as any)._lineHeightHandlers;
  }
});
</script>

<style scoped lang="scss">
.line-height-dropdown {
  padding: 4px 0;
  margin: 0;
  list-style: none;
  background: var(--editor-color-white);
  border-radius: var(--editor-radius-medium);
  min-width: 120px;
}

.line-height-dropdown :deep(.dropdown-item) {
  padding: 8px 12px;
  font-size: var(--editor-font-size);
  color: var(--editor-text-color);
  transition: background-color 0.2s;
  user-select: none;

  &.is-selected {
    color: var(--editor-primary-color);
    background-color: var(--editor-content-node-selected-background);
    font-weight: 500;
  }

  .dropdown-item-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }
}

.line-height-label {
  flex: 1;
}

.line-height-check {
  color: var(--editor-primary-color);
  font-size: 16px;
  width: 16px;
  height: 16px;
  flex-shrink: 0;
  margin-left: 8px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
</style>
